package com.base.myproject.client.HR.recruitment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.base.myproject.client.HR.bcode.BcodeSelectDialog;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxX;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;

/**
 * @author cxghiu4102@gmail.com 2010-11-3 安排面试人员
 * 
 */
public class ArrangeInterview extends BaseJDBCPanel {
	private Set<Map<String, Object>> list = new HashSet<Map<String, Object>>();
	private Button submit = new Button("提交安排");
	
	BcodeSelectDialog<TreeNodeModelData> bsd_add;
	List<Map<String, String>> bcodeList;

	public ArrangeInterview() {
		init();
		submit.addListener(Events.OnClick, getListener());
	}

	public void init() {
		initwidget();
	}

	private void initwidget() {
		VerticalPanel vp = new VerticalPanel();
		HorizontalPanel hp = new HorizontalPanel();
		hp.add(submit);
		vp.setSpacing(5);
		FieldSet fs1 = new FieldSet();
		fs1.add(createForm());
		fs1.setHeading("面试安排");
		vp.add(fs1);
		vp.add(hp);
		add(vp);
	}

	FormPanel form = null;
	BaseComboBoxX C_num4;
	DateField C_num6;
	TextField<String> C_num7;

	private FormPanel createForm() {
		FormPanel form = new FormPanel(); // false设置让form不会提示用户新
		// 增加东西，由grid控制增加
		TableLayout tl = new TableLayout(8);
		form.setBodyBorder(false);
		form.setPadding(4);

		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);

		form.setLayout(tl);
		form.setHeaderVisible(false);
		
		form.add(new Label("面试人员:"), td);
		bsd_add = new BcodeSelectDialog<TreeNodeModelData>() {
			public void doposted(List<TreeNodeModelData> modeldatalist) {
				if (modeldatalist.size() > 0) {
					bcodeList = new ArrayList<Map<String, String>>();
					String bcode_str = "";
					String systemid = "";
					String bcode = "";
					Map<String, String> map = null;
					for (int i = 0; i < modeldatalist.size(); i++) {
						map = new HashMap<String, String>();
						TreeNodeModelData model = modeldatalist.get(i);
						bcode_str = bcode_str + ";"
								+ model.get("bname");
						bcode = model.get("bcode");
						if (bcode == null || bcode.equals(""))
							MessageBox.alert("提示", "面试官只能是部门人员，不能是部门，新重新选择，谢谢", null);
						systemid = (String) model.getParent().get("systembcode");
						map.put("bcode", bcode);
						map.put("systemid", systemid);
						bcodeList.add(map);  //用bcodeList保存所有选中员工的bcode
					}
					bcode_str = bcode_str.substring(1, bcode_str.length());
					this.setEmptyText(bcode_str);  //一旦Dialog选择了员工，就让bsd_add显示所有选中员工的名字
				}
			}
		};
		bsd_add.setNeesreselect(false);
		bsd_add.setEmptyText("未选择人员");
		bsd_add.setExpanded();
		bsd_add.setEditable(false);
		form.add(bsd_add, td);
		
		form.add(new Label("面试时间:"), td);
		C_num6 = new DateField();
		C_num6.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd HH:mm"));
		form.add(C_num6, td);

		form.add(new Label("面试地点:"), td);
		C_num7 = new TextField<String>();
		form.add(C_num7, td);
		
		return form;
	}

	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				try {
					submit.setEnabled(false);
					String selectSql = "select * from (";
					for (Map<String, Object> map : list) {
						long icode = (Long) map.get("icode");
						String requestNo = (String) map.get("requestNo");
						String sql = "select isnull(max(number),0) maxNumber from hr_interview where positionRequestId = '" 
							+ icode + "' and interviewNo = '" + requestNo + "' union all ";
						selectSql = selectSql + sql;
					}
					selectSql = selectSql.substring(0, selectSql.length() - 11) + ") as a";
					selectMaxNumber(selectSql);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

		};
		return defaultlistener;
	}
	
	/**
	 * @param lists
	 *            要执行的sql语句
	 * @return 执行成功与否 执行所有的insert语句，完全安排面试的操作
	 */
	public boolean interviewSubmit(List<String> lists) {
		CommandSyncsql csql = new CommandSyncsql();// 执行sql命令
		for (String sql : lists) {
			csql.getV().add(sql);
		}
		if (csql.getV().size() <= 0) {
			return false;
		} else {
			CommandSyncContainer cc = new CommandSyncContainer();// 可以添加的命令
			cc.add(csql);

			GreetingServiceAsync greetingService = GWT
					.create(GreetingService.class);
			greetingService.SendCommandSync(cc,
					new AsyncCallback<CommandSyncReturnObject>() {
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("错误", "网络连接失败", null);
						}

						@Override
						public void onSuccess(CommandSyncReturnObject result) {
							if (result.isB()) {
								Info.display("提示信息", "安排面试成功，安排的面试人数为" + list.size() + "人");
							} else {
								MessageBox.alert("错误", "错误，错误代码"
										+ result.getMessage(), null);

							}
						}
					});
		}
		return true;
	}
	
	public void selectMaxNumber(String select) {
		final GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService.getDataSet(select, new AsyncCallback<DataSet>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(DataSet result) {
				if (result.getRowCount() > 0) {
					List<String> insertSqlList = new LinkedList<String>();
					String sql = "";
					Iterator<Map<String, Object>> it = null;
					for (Map<String, String> map : bcodeList) {
						it = list.iterator();
						for (int i=0; it.hasNext(); i++) {
							Map<String, Object> interviewMap = it.next();
							sql = "insert hr_interview(interviewNo,depCode,positionRequestId,interviewPeopleId,number, interviewDate, place) values('"
								+ interviewMap.get("requestNo") + "','" + map.get("systemid") + "'," + interviewMap.get("icode") + ",'"
								+ map.get("bcode") + "'," + (Integer.parseInt(result.getValue(i, "maxNumber")) + 1) + ", '" + C_num6.getRawValue() + "', '" + C_num7.getRawValue() + "')";
							insertSqlList.add(sql);
						}
					}
					interviewSubmit(insertSqlList);
				}
			}
		});
	}

	public Set<Map<String, Object>> getList() {
		return list;
	}

	public void setList(Set<Map<String, Object>> list) {
		this.list = list;
	}

}
